package com.yisu.expressway.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;

import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yisu.expressway.login.LoginPageActivity;
import com.yisu.expressway.model.LoginEvent;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.model.UserProfile;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import com.yisu.expressway.R;

/**
 * Created by date13 on 16/2/27.
 */
public class SocialUtils {
    private static final String tag = "SocialUtils";
    private static UMShareAPI mShareAPI = null;
    private static SHARE_MEDIA platform = null;
    public static final Map<Integer,SHARE_MEDIA> mediaLoginMap = new HashMap<Integer,SHARE_MEDIA>();
    private static final Map<Integer,SHARE_MEDIA> mediaShareMap = new HashMap<Integer,SHARE_MEDIA>();
    private static final String logo = "http://pili-static.huacehuaban.com/default_share_120.png";

    public static final String APPID_QQ = "1105631744";
    public static final String SECRET_QQ = "hquLIhi8G2kbE5kw";
    public static final String APPID_WEIXIN = "wxdfb711db9324f0d5";
    public static final String SECRET_WEIXIN = "33a0930cee276dd271e3b6981fb0905c";
    public static final String APPID_WEIBO = "3492452553";//"4273011226";
    public static final String SECRET_WEIBO = "c28ca3ae9d5bba91ff11d1acf5b2453b";//"fc659759805aeeca755b48d26f2e5f53";


    public static String head;

    private static final String CHANNEL_SEPARATOR = "#";
    static{
        mediaLoginMap.put(1,SHARE_MEDIA.WEIXIN);
        mediaLoginMap.put(2,SHARE_MEDIA.QQ);
        mediaLoginMap.put(3,SHARE_MEDIA.SINA);

        mediaShareMap.put(0,SHARE_MEDIA.SINA);
        mediaShareMap.put(1,SHARE_MEDIA.WEIXIN);
        mediaShareMap.put(2,SHARE_MEDIA.WEIXIN_CIRCLE);
        mediaShareMap.put(3,SHARE_MEDIA.QQ);
        mediaShareMap.put(4,SHARE_MEDIA.QZONE);
    }

    public static void initDialog(Activity curActivity,String str){
        ProgressDialog dialog =  new ProgressDialog(curActivity);
        dialog.setTitle("信息");
        dialog.setMessage(str);
        dialog.setIndeterminateDrawable(curActivity.getResources().getDrawable(R.drawable.round_progress));
        Config.dialog = dialog;
    }
    public static void init(){
        //微信    wx12342956d1cab4f9,a5ae111de7d9ea137e88a5e02c07c94d
        PlatformConfig.setWeixin(APPID_WEIXIN, SECRET_WEIXIN);

        //新浪微博
        PlatformConfig.setSinaWeibo(APPID_WEIBO, SECRET_WEIBO);
        Config.REDIRECT_URL="http://sns.whalecloud.com/sina2/callback";

        // QQ
        PlatformConfig.setQQZone(APPID_QQ, SECRET_QQ);



        Config.IsToastTip = false;
//        Tencent.createInstance(APPID_QQ, activity.getApplicationContext());
    }

    public static void authLogin(final LoginPageActivity curActivity, final Integer type){
        mShareAPI = UMShareAPI.get(curActivity);
        platform = mediaLoginMap.get(type);
        initDialog(curActivity, "登录...");

        curActivity.showLoading();

        mShareAPI.doOauthVerify(curActivity, platform, new UMAuthListener() {
            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                HBLog.d("test", "success");
                final String accessToken = map.get("access_token");
                curActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mShareAPI.getPlatformInfo(curActivity, platform, new UMAuthListener() {
                            @Override
                            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

                                ToastUtil.displayShortToastMsg(curActivity, "登录中....");
                                thirdLogin(type, accessToken, curActivity, map);

                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                                ToastUtil.displayShortToastMsg(curActivity, "获取用户信息错误");
                                curActivity.dismissLoading();
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media, int i) {
                                curActivity.dismissLoading();
                            }
                        });
                    }
                });
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                ToastUtil.displayShortToastMsg(curActivity, "登录错误");
                curActivity.dismissLoading();
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                ToastUtil.displayLongToastMsg(curActivity, "取消登录");
                curActivity.dismissLoading();
            }
        });

    }

    public static void thirdLogin(final Integer type,String accessToken,final LoginPageActivity curActivity,Map<String, String> map){
        Map<String,Object> params = new HashMap<>();

        params.put("accountType",type);
        params.put("deviceType",2);
        if(!StringUtil.isNullOrEmpty(LoginManager.getPushClientId())){
            params.put("pushType",1);
            params.put("pushClientId",LoginManager.getPushClientId());
        }

        if (type == UserProfile.LOGIN_TYPE_WEIXIN){//wx
            params.put("userAccount", map.get("unionid"));
            params.put("userName", map.get("nickname"));
            params.put("avatarUrl", map.get("headimgurl"));
        }
        if (type == UserProfile.LOGIN_TYPE_WEIBO){//sina
            params.put("userAccount", map.get("uid"));
            params.put("userName", map.get("screen_name"));
            params.put("avatarUrl", map.get("profile_image_url"));

        }
        if (type == UserProfile.LOGIN_TYPE_QQ){
            params.put("userAccount", map.get("openid"));
            params.put("userName", map.get("screen_name"));
            params.put("avatarUrl", map.get("profile_image_url"));
        }

        ApiClientHelper.postApi(ApiSetting.loginIn(), new TypeToken<UserProfile>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<UserProfile>>() {
            @Override
            public void onResponse(final ApiResult<UserProfile> userProfileApiResult) {
                curActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        curActivity.dismissLoading();

                        if (!userProfileApiResult.success) {
                            ToastUtil.displayShortToastMsg(curActivity, "登录失败:" + userProfileApiResult.getMsg());
                            EventBus.getDefault().post(new LoginEvent(false));
                            return;
                        }

                        UserProfile user = userProfileApiResult.getResult();

                        LoginManager.onLoginSuccess(user);
                        ToastUtil.showMessage(curActivity, "登录成功");
                        EventBus.getDefault().post(new LoginEvent(true));
//                        curActivity.finish();


                        if (mLoginListener != null) {
                            mLoginListener.onLogin();
                        }
                    }
                });

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(curActivity, "登录失败");
                EventBus.getDefault().post(new LoginEvent(false));
                curActivity.dismissLoading();
            }
        }, curActivity);
    }

    private static void startTargetActivity(Activity curActivity,Class targetClass) {
        Intent mIntent = new Intent(curActivity, targetClass);
        curActivity.startActivity(mIntent);
        curActivity.finish();
    }

    private static void startTargetActivity(Activity curActivity,Class targetClass,String head) {
        Intent mIntent = new Intent(curActivity, targetClass);
        mIntent.putExtra("head",head);
        curActivity.startActivity(mIntent);
        curActivity.finish();
    }


//    public static void share(final Activity curActivity,final Integer shareType,final ShareObj shareObj){
//        share(curActivity, shareType, shareObj, null);
//    }

//    public static void share(final Activity curActivity,final Integer shareType,final ShareObj shareObj, final UMShareListener umShareListener){
//        Map<String,Object> params = new HashMap<>();
//        params.put("contentType",shareObj.getShareStyle());
//        if(shareObj.getShareStyle() == ShareObj.STYLE_TALENT_STYLE){
//            params.put("talentId",shareObj.getTalentId());
//        }
//        params.put("eventId",shareObj.getShareId());
//        params.put("targetType", shareType);
////        ActivityLoading.showLoading(curActivity, R.layout.activity_loading_simple);
//        ApiClientHelper.postApi(ApiSetting.share(), new TypeToken<ShareResult>() {
//        }, new JSONObject(params), new Response.Listener<ApiResult<ShareResult>>() {
//            @Override
//            public void onResponse(ApiResult<ShareResult> result) {
//
//                //bug#889, 【Android】【分享】【100%】分享一个被删除的动态，提示“分享失败：分享参数错误”，且提示后一直转圈圈
//                ActivityLoading.dismiss(curActivity);
//
//                if (curActivity == null || curActivity.isDestroyed())
//                    return;
//
//                if (!result.success) {
//                    ToastUtil.displayLongToastMsg(curActivity, "分享失败:" + result.getMsg());
//                    return;
//                }
//                if (shareObj.getShareStyle() == ShareObj.STYLE_APP) {//下载
//                    HashMap<String, String> value = new HashMap<String, String>();
//                    value.put("currentPage", "" + curActivity.getClass());
//                    MobclickAgent.onEvent(curActivity, AnalysisConstant.EVENT_SHARE_CLIENT, value);
//                }
//                if (shareObj.getShareStyle() == ShareObj.STYLE_ACTIVITY) {//活动
//                    HashMap<String, String> value = new HashMap<String, String>();
//                    value.put("currentPage", "" + curActivity.getClass());
//                    MobclickAgent.onEvent(curActivity, AnalysisConstant.EVENT_SHARE_SUBJECT, value);
//                }
//                if (shareObj.getShareStyle() == ShareObj.STYLE_USER) {//主页
//                    HashMap<String, String> value = new HashMap<String, String>();
//                    value.put("currentPage", "" + curActivity.getClass());
//                    MobclickAgent.onEvent(curActivity, AnalysisConstant.EVENT_SHARE_HOME_PAGE, value);
//                }
//                if (shareObj.getShareStyle() == ShareObj.STYLE_TREND) {//主题
//                    HashMap<String, String> value = new HashMap<String, String>();
//                    value.put("currentPage", "" + curActivity.getClass());
//                    value.put("type", "");
//                    MobclickAgent.onEvent(curActivity, AnalysisConstant.EVENT_SHARE_TREND, value);
//                }
//
//                final ShareResult shareResult = result.getResult();
//                UMImage image = new UMImage(curActivity, StringUtil.isNullOrEmpty(shareResult.getShareImg()) ? logo : shareResult.getShareImg() + "?imageView2/1/w/200/h/200");
////                initDialog(curActivity,"分享中...");
//
//                initDialog(curActivity, "开始分享...");
//                HBLog.d("share", shareResult.toString());
//                HBLog.d("share", shareObj.toString());
//
//                //微信朋友圈，分享时使用content
//                String title = shareResult.getTitle();
//                String content = shareResult.getContent();
//                String tmp;
//                if (SHARE_MEDIA.WEIXIN_CIRCLE == mediaShareMap.get(shareType)) {
//                    tmp = title;
//                    title = content;
//                    content = tmp;
//                }
//
//                new ShareAction(curActivity)
//                        .setPlatform(mediaShareMap.get(shareType))
//                        .setCallback(umShareListener == null ? new SimpleUMShareListener(curActivity)
//                                : umShareListener)
//                        .withTitle(title)
//                        .withText(content)
//                        .withTargetUrl(shareResult.getShareUrl())
//                        .withMedia(image)
//                        .share();
//
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//
//                //bug#889, 【Android】【分享】【100%】分享一个被删除的动态，提示“分享失败：分享参数错误”，且提示后一直转圈圈
//                ActivityLoading.dismiss(curActivity);
//
//                if (curActivity == null || curActivity.isDestroyed())
//                    return;
//                ToastUtil.displayLongToastMsg(curActivity, "登录失败");
//            }
//        }, curActivity);
//
//    }


    public static UMShareAPI getmShareAPI() {
        return mShareAPI;
    }

    public static void setmShareAPI(UMShareAPI mShareAPI) {
        SocialUtils.mShareAPI = mShareAPI;
    }


    /**
     * 通用分享回调监听
     */
    public static class SimpleUMShareListener implements UMShareListener {

        private Activity mActivity;

        public SimpleUMShareListener(Activity activity) {
            mActivity = activity;
        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            if (mActivity != null) {
                ToastUtil.displayLongToastMsg(mActivity, "分享成功");
            }
            onComplete(share_media);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            if (mActivity != null && throwable != null) {
                ToastUtil.displayLongToastMsg(mActivity, "分享失败:"+throwable.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            // 部分分享成功后也会回调 onCancel
//            if (mActivity != null) {
//                ToastUtil.displayLongToastMsg(mActivity, "分享取消");
//            }
//            onComplete(share_media);
        }

        /**
         * 分享成功通知服务器
         * @param share_media
         */
        public void onComplete(SHARE_MEDIA share_media) {

        }
    }

    private static OnLoginListener mLoginListener = null;
    public static void setOnLoginListener(OnLoginListener listener){
        mLoginListener = listener;
    }
    public interface OnLoginListener{
        public void onLogin();
        public void onLoginFailed();
        public void enterTargetActivity(UserProfile user, Activity activity, String head);
    }
}
